package com.ailesson.order.service.impl;

import com.ailesson.common.except.GlobalErrorCodeConstants;
import com.ailesson.common.except.ServiceException;
import com.ailesson.common.reply.R;
import com.ailesson.user.dto.UserInfoSimpleDto;
import com.ailesson.user.feign.UserFeignClient;
import com.google.common.base.Functions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;

import com.ailesson.order.mapper.CouponUseMapper;
import com.ailesson.order.entity.CouponUseEntity;
import com.ailesson.order.service.CouponUseService;
import com.ailesson.order.model.req.CouponUseQueryReq;
import com.ailesson.order.model.req.CouponUseReq;
import com.ailesson.order.model.reply.CouponUseReply;
import com.ailesson.common.reply.PageResult;
import cn.hutool.core.collection.CollectionUtil;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Slf4j
@Service
public class CouponUseServiceImpl extends ServiceImpl<CouponUseMapper, CouponUseEntity> implements CouponUseService {

    @Autowired
    private UserFeignClient userFeignClient;
    @Override
    public PageResult queryPage(CouponUseQueryReq params) {
       Page pageTmp = Page.of(params.getPageNo(),params.getPageSize());
       IPage<CouponUseEntity> page = this.page(
               pageTmp,
               new LambdaQueryWrapper<CouponUseEntity>()
                       .orderByDesc(CouponUseEntity::getId)
                       .eq(params.getCouponId() != null,CouponUseEntity::getCouponId,params.getCouponId())
                       .eq(params.getCouponStatus() != null,CouponUseEntity::getCouponStatus,params.getCouponStatus())
                       .ge(StringUtils.hasText(params.getGetTimeBegin()),CouponUseEntity::getGetTime,params.getGetTimeBegin())
                       .le(StringUtils.hasText(params.getGetTimeEnd()),CouponUseEntity::getGetTime,params.getGetTimeEnd())
       );
       List<CouponUseReply> replyList = Collections.EMPTY_LIST;
       if (CollectionUtil.isNotEmpty(page.getRecords())){
           replyList = page.getRecords().stream().map(x -> {
               CouponUseReply reply = new CouponUseReply();
               BeanUtils.copyProperties(x, reply);
               return reply;
           }).collect(Collectors.toList());
           fillUserInfo(replyList);
       }
       return new PageResult<>(replyList,page.getTotal());
    }

    private void fillUserInfo(List<CouponUseReply> replyList) {
        List<Long> ids = replyList.stream().map(CouponUseReply::getUserId).collect(Collectors.toList());
        R<List<UserInfoSimpleDto>> simpleR = userFeignClient.batchSimple(ids);
        if (simpleR.ifSuccess() && CollectionUtil.isNotEmpty(simpleR.getData())){
            Map<Long, UserInfoSimpleDto> collect = simpleR.getData().stream().collect(Collectors.toMap(UserInfoSimpleDto::getId, Functions.identity()));
            replyList.forEach(x -> {
                UserInfoSimpleDto simpleDto = collect.get(x.getUserId());
                x.setNickName(simpleDto != null?simpleDto.getNickName():null);
                x.setPhone(simpleDto != null?simpleDto.getPhone():null);
            });
        }
    }

    @Override
    public CouponUseReply info(Long id) {
        CouponUseEntity entity = this.getById(id);
        if (entity != null){
            CouponUseReply reply = new CouponUseReply();
            BeanUtils.copyProperties(entity, reply);
            return reply;
        }
        return null;
    }

    @Transactional(
            rollbackFor = {Exception.class}
    )
    @Override
    public void update(CouponUseReq couponUse) {
        if (couponUse.getId() == null || couponUse.getId() <= 0){
            throw new ServiceException(GlobalErrorCodeConstants.ID_EMPTY_ERROR);
        }
        CouponUseEntity entity = this.getById(couponUse.getId());
        if (entity == null){
            throw new ServiceException(GlobalErrorCodeConstants.NOT_EXISTS_ERROR);
        }
        BeanUtils.copyProperties(couponUse, entity);
        this.updateById(entity);
    }

    @Transactional(
            rollbackFor = {Exception.class}
    )
    @Override
    public Long add(CouponUseReq couponUse) {
        couponUse.setId(null);
        CouponUseEntity entity = new CouponUseEntity();
        BeanUtils.copyProperties(couponUse, entity);
        this.save(entity);
        return entity.getId();
    }

}